import { copyFileSync, mkdirSync, existsSync, createWriteStream, readFileSync } from "fs";
import { resolve, dirname } from "path";
import { fileURLToPath } from "url";
import archiver from "archiver";

// 在ES模块中获取__dirname的替代方法
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// 手动读取JSON文件
const dataInfoPath = resolve(__dirname, "./src/part/dataInfo.json");
if (!existsSync(dataInfoPath)) {
  throw new Error(`dataInfo.json 文件不存在: ${dataInfoPath}`);
}
const dataInfo = JSON.parse(readFileSync(dataInfoPath, "utf8"));

// 组件名称和输出目录配置
const componentName = dataInfo.name;
if (!componentName) {
  throw new Error("dataInfo.json 中未定义组件名称 (name)");
}

const outputDir = resolve(__dirname, `dist/${componentName}`);
const distRoot = resolve(__dirname, "dist");

try {
  // 确保输出目录存在
  if (!existsSync(outputDir)) {
    mkdirSync(outputDir, { recursive: true });
    console.log(`[compress] 已创建输出目录: ${outputDir}`);
  }

  // 复制必要文件
  const srcDir = resolve(__dirname, "src/part");
  const filesToCopy = ["dataInfo.json", "publicFun.json", "preview.png"];
  let copySuccessCount = 0;

  filesToCopy.forEach((file) => {
    const srcPath = resolve(srcDir, file);
    const destPath = resolve(outputDir, file);
    
    if (existsSync(srcPath)) {
      copyFileSync(srcPath, destPath);
      copySuccessCount++;
      console.log(`[compress] 已复制: ${file}`);
    } else {
      console.warn(`[compress] 未找到文件，已跳过: ${srcPath}`);
    }
  });

  console.log(`[compress] 文件复制完成，成功复制 ${copySuccessCount}/${filesToCopy.length} 个文件`);

  // 创建ZIP压缩包
  const zipFilePath = resolve(distRoot, `${componentName}.zip`);
  const zipOutput = createWriteStream(zipFilePath);
  const archive = archiver("zip", { zlib: { level: 9 } });

  // 事件监听
  zipOutput.on("close", () => {
    const sizeKB = (archive.pointer() / 1024).toFixed(2);
    console.log(`[compress] 压缩包创建成功: ${zipFilePath}`);
    console.log(`[compress] 压缩包大小: ${sizeKB} KB`);
  });

  archive.on("warning", (warn) => {
    console.warn(`[compress] 压缩警告: ${warn.message}`);
  });

  archive.on("error", (err) => {
    throw new Error(`[compress] 压缩失败: ${err.message}`);
  });

  // 执行压缩
  archive.pipe(zipOutput);
  archive.directory(outputDir, false);
  archive.finalize();

} catch (error) {
  const errorMsg = error instanceof Error ? error.message : String(error);
  console.error(`[compress] 错误: ${errorMsg}`);
  process.exit(1); // 发生错误时退出并返回非0状态码
}
    